import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import store from '@/store/index'
import {Message} from 'element-ui'

Vue.use(Router)

const router = new Router({
  routes
})

router.beforeEach(async (to, from, next) => {
  const token = store.state.auth.token
  this.token = 'bod_token_2_48'//先写死
  if (to.name === 'login') {
    next()
    return
  }
  if (!token) {
    next({ name: 'login' })
  } else {
    if (!store.state.auth.menus) {
      try {
        await store.dispatch('auth/getAuths')
      } catch(e) {
        Message.warning(e.message)
        next({name: 'login'})
      }
    }
    // 未设置权限
    if (!to.meta || !to.meta.access) {
      next()
    } else {
      const menuMap = store.getters['auth/menuMap']
      if (menuMap[to.meta.access]) {
        next()
      } else {
        Message.warning('无权限')
        if (!from.name) {
          next({ name: 'login' })
        } else {
          next(false)
        }
      }
    }
  }
})

export default router
